var rootPath = getRootPath();
$(function() {
	focusById();
	var callbackUrl = getUrlParam("callbackUrl");//getUrlParam 带转义
	
	$("#save").click(function() {
		if(!checkData()){
			return;
		}
		
		if(oriBankAccount != $("#bankAccount").val() 
				&& !checkBankAccount($("#bankAccount").val())) {
			return;
		}
		
		//数据长度校验
		if($("#accountName").val().length > 200) {
			$("#accountName").focus();
			showErrMsg("accountName", "账户名称输入过长,请精简");
			return;
		}
		
		if($("#bankAccount").val().length > 50) {
			$("#bankAccount").focus();
			showErrMsg("bankAccount","银行账号输入过长,请精简");
			return;
		}
		
		if($("#depositBank").val().length > 50) {
			$("#depositBank").focus();
			showErrMsg("depositBank","开户行输入过长,请精简");
			return;
		}
		
		if($("#aopenBranch").val().length > 200) {
			$("#aopenBranch").focus();
			showErrMsg("aopenBranch","开户支行输入过长,请精简");
			return;
		}
		
		showLoading();
		$.ajax({
			url: rootPath + '/userDetailFront/save',
	        type: 'PUT',
	        contentType: 'application/json;charset=UTF-8',
	        data: JSON.stringify($("#bankInfoForm").serializeJson()),
	        success: function (data) {
	        	hideLoading();
	        	if('0000' == data.returnCode) {
	        		layer.msg('保存成功',{icon:6,time:1000},function() {
	        			if(callbackUrl){
							parent.document.location.href = callbackUrl;
						}else{
							parent.$("#content").prop("src", "bankInfoShow.html");
						}
	        		});
	        	} else {
	        		layer.alert(data.returnMessage);
	        	}
	        },
	        error: function (jqXHR, textStatus, errorThrown) {
	        	hideLoading();
	        	layer.alert("error");
	        }
	    });
	});
});

function checkData(){
	if($("#accountName").val() == '') {
		$("#accountName").focus();
		showErrMsg("accountName","请输入账户名");
		
		return false;
	}
	if($("#bankAccount").val() == '') {
		$("#bankAccount").focus();
		showErrMsg("bankAccount","请输入银行账号");
		
		return false;
	}
	if($("#depositBank").val() == '') {
		$("#depositBank").focus();
		showErrMsg("depositBank","请输入开户行");
		
		return false;
	}
	if($("#aopenBranch").val() == '') {
		$("#aopenBranch").focus();
		showErrMsg("aopenBranch","请输入开户支行");
		
		return false;
	}
	
	if($("#aopenProvince").val() == '') {
		$("#aopenProvince").focus();
		showErrMsg("aopenProvince","请选择开户所在省");
		
		return false;
	}
	if($("#aopenCity").val() == '') {
		$("#aopenCity").focus();
		showErrMsg("aopenCity","请选择开户所在市");
		return false;
	}
	return true;
}

//检查银行卡号
function checkBankAccount(bankAccount) {
    var bankAccount = bankAccount.replace(/\s/g,'');
    if(bankAccount == "") {
        showErrMsg("bankAccount", "请填写银行账号");
        return false;
    }
    if(bankAccount.length < 16 || bankAccount.length > 19) {
    	showErrMsg("bankAccount", "银行账号长度必须在16到19之间");
        return false;
    }
    var num = /^\d*$/;//全数字
    if(!num.exec(bankAccount)) {
    	showErrMsg("bankAccount", "银行账号必须全为数字");
        return false;
    }
    //开头6位
    var strBin = "10,18,30,35,37,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,58,60,62,65,68,69,84,87,88,94,95,98,99";
    if(strBin.indexOf(bankAccount.substring(0, 2)) == -1) {
    	showErrMsg("bankAccount", "银行账号开头6位不符合规范");
        return false;
    }
    //Luhn校验
    if(!luhnCheck(bankAccount)){
        return false;
    }
    return true;
}

/**
 * 银行卡号Luhn校验算法
	luhn校验规则：16位银行卡号（19位通用）: 
	1.将未带校验位的 15（或18）位卡号从右依次编号 1 到 15（18），位于奇数位号上的数字乘以2。
	2.将奇位乘积的个十位全部相加，再加上所有偶数位上的数字。
	3.将加法和加上校验位能被 10 整除。
 * @param bankAccount	银行账号
 * @returns {Boolean}
 */
 function luhnCheck(bankAccount){
    var lastNum = bankAccount.substr(bankAccount.length-1,1);//取出最后一位（与luhn进行比较）
    var first15Num = bankAccount.substr(0,bankAccount.length-1);//前15或18位
    var newArr = new Array();
    for(var i = first15Num.length-1;i > -1;i--){    //前15或18位倒序存进数组
        newArr.push(first15Num.substr(i,1));
    }
    var arrJiShu = new Array();  //奇数位*2的积 <9
    var arrJiShu2 = new Array(); //奇数位*2的积 >9
    var arrOuShu = new Array();  //偶数位数组
    for(var j = 0;j < newArr.length;j++) {
        if((j + 1) % 2 == 1){//奇数位
            if(parseInt(newArr[j]) * 2 < 9) {            	
            	arrJiShu.push(parseInt(newArr[j]) * 2);
            } else {            	
            	arrJiShu2.push(parseInt(newArr[j])*2);
            }
        } else { //偶数位        	
        	arrOuShu.push(newArr[j]);
        } 
    }
    
    var jishu_child1 = new Array();//奇数位*2 >9 的分割之后的数组个位数
    var jishu_child2 = new Array();//奇数位*2 >9 的分割之后的数组十位数
    for(var h = 0;h < arrJiShu2.length;h++) {
        jishu_child1.push(parseInt(arrJiShu2[h]) % 10);
        jishu_child2.push(parseInt(arrJiShu2[h]) / 10);
    }        
    
    var sumJiShu = 0; //奇数位*2 < 9 的数组之和
    var sumOuShu = 0; //偶数位数组之和
    var sumJiShuChild1 = 0; //奇数位*2 >9 的分割之后的数组个位数之和
    var sumJiShuChild2 = 0; //奇数位*2 >9 的分割之后的数组十位数之和
    var sumTotal = 0;
    for(var m = 0;m < arrJiShu.length;m++) {
        sumJiShu = sumJiShu + parseInt(arrJiShu[m]);
    }
    
    for(var n = 0;n < arrOuShu.length;n++) {
        sumOuShu = sumOuShu + parseInt(arrOuShu[n]);
    }
    
    for(var p = 0;p < jishu_child1.length;p++) {
        sumJiShuChild1 = sumJiShuChild1 + parseInt(jishu_child1[p]);
        sumJiShuChild2 = sumJiShuChild2 + parseInt(jishu_child2[p]);
    }      
    //计算总和
    sumTotal = parseInt(sumJiShu) + parseInt(sumOuShu) + parseInt(sumJiShuChild1) + parseInt(sumJiShuChild2);
    
    //计算luhn值
    var k = parseInt(sumTotal) % 10 == 0 ? 10 : parseInt(sumTotal) % 10;        
    var luhn = 10-k;
    
    if(lastNum == luhn) {
        return true;
    } else {
    	showErrMsg("bankAccount", "银行账号必须符合luhn校验");
        return false;
    }     
}

function showErrMsg(id,msg) {
	$("#" + id + "Tip").text(msg);
	$("#" + id + "Msg").show();
}

function hideMsg(id) {
	$("#" + id + "Msg").hide();
}

function focusById() {
	$("#accountName").focus(function() {
		hideMsg("accountName");
	});
	$("#bankAccount").focus(function() {
		hideMsg("bankAccount");
	});
	$("#depositBank").focus(function() {
		hideMsg("depositBank");
	});
	$("#aopenBranch").focus(function() {
		hideMsg("aopenBranch");
	});
}